package com.financing.platform.web.api;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.platform.common.Pager;
import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;
import com.financing.platform.dto.CountInfoDTO;
import com.financing.platform.dto.FaUserDTO;
import com.financing.platform.service.ICountInfoService;
import com.financing.platform.service.IFaUserService;
import com.financing.platform.util.CsvExportUtil;
import com.financing.platform.util.Dict;
import com.financing.platform.util.SecureUtil;
import com.financing.platform.util.StringUtil;
import com.financing.platform.vo.AuthUserDetailedListVO;
import com.financing.platform.vo.OrderDetailedListVO;
import com.financing.platform.vo.SalesPerformanceVO;

/**
 * 
 * @ClassName: CountInfoAction
 * @Description: 统计信息Action 
 * @author  qiye
 * @date 2014年10月31日 上午9:52:17
 *
 */
@Controller("countInfoActionAPI")
@RequestMapping("/api")
@Scope("prototype")
public class CountInfoAction extends BaseAction{
	
	@Autowired
	private ICountInfoService countInfoServiceImpl;
	
	@Autowired
	IFaUserService faUserServiceImpl;
	
	DecimalFormat    df   = new DecimalFormat("######0.00"); 
	
	/**
	 * 
	 * @Title: queryCountInfo
	 * @Description: 运营信息统计 
	 * @param @param request
	 * @param @param response
	 * @param @param countInfoDTO
	 * @param @return   
	 * @return ModelAndView   
	 * @throws
	 */
	@RequestMapping("/queryCountInfo.shtml")
	@ResponseBody
	public ResultMap queryCountInfo(HttpServletRequest request,
			HttpServletResponse response,String countDateBeginStr, String countDateEndStr) {
		
		try{
			this.log.info("begin query count info!");
			
			request.getSession().setAttribute(Dict.requestID, "queryCountInfo.shtml");
			
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			
			Map<String,Object> params = new HashMap<String,Object>();
			
			Date countDateBegin = null;
			
			Date countDateEnd = null;
			
				if(countDateBeginStr == null){
					countDateBegin = StringUtil.rollDay(new Date(), -1);
					countDateBegin = df.parse(df.format(countDateBegin));
				}else{
					countDateBegin = df.parse(countDateBeginStr);
				}
				
				if(countDateEndStr == null){
					countDateEnd = countDateBegin;
				}else{
					countDateEnd = df.parse(countDateEndStr);
				}
				
				params.put("countDateBegin",countDateBegin );
				params.put("countDateEnd", countDateEnd);
				
				List<CountInfoDTO> countInfoList = countInfoServiceImpl.queryCountInfoList(params);
				
				resultMap.setAttribute(countInfoServiceImpl.queryTotalCountInfo());
				
				resultMap.setAttribute("countInfoList", countInfoList);
				resultMap.setAttribute("countDateBegin",countDateBegin);
				resultMap.setAttribute("countDateEnd", countDateEnd);
				resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
				this.log.info("end query count info access !");
			}catch(Exception e){
				log.error("date format error!",e);
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}
		
		return resultMap;
	}
	/**
	 * 
	 * @Title: queryCountInfo
	 * @Description: 运营信息统计 
	 * @param @param request
	 * @param @param response
	 * @param @param countInfoDTO
	 * @param @return   
	 * @return ModelAndView   
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryOrderDetailedList.shtml")
	@ResponseBody
	public ResultMap queryOrderDetailedList(HttpServletRequest request,
			HttpServletResponse response,OrderDetailedListVO orderDetailedListVO,Pager pager) {
		
		
		log.info("In queryOrderDetailedList begin!");
		
		try{
			
			orderDetailedListVO.setBegin(pager.getStartIndex());
			orderDetailedListVO.setPageSize(pager.getPageSize());
			
			
			int count = countInfoServiceImpl.queryOrderDetailedListCount(orderDetailedListVO);
			
			pager.setTotalCount(count);
			
			List<OrderDetailedListVO> list;
			if(count>0){
				list = countInfoServiceImpl.queryOrderDetailedList(orderDetailedListVO);
			}else{
				list = Collections.EMPTY_LIST;
			}
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			resultMap.setAttribute("list",list);
			resultMap.setAttribute("pager",pager);
		}catch(Exception e){
			log.error("queryOrderDetailedList error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
		log.info("In queryOrderDetailedList end!");	
		
		return resultMap;
	}
	/**
	 * 
	 * @Title: queryOrderDetailedListCsv
	 * @Description: 导出订单清单
	 * @param @param request
	 * @param @param response
	 * @param @param countInfoDTO
	 * @param @return   
	 * @return ModelAndView   
	 * @throws
	 */
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/queryOrderDetailedListCsv.shtml")
	public void queryOrderDetailedListCsv(HttpServletRequest request,
			HttpServletResponse response,OrderDetailedListVO orderDetailedListVO) {
		
		
		log.info("In queryOrderDetailedListCsv begin!");
		
		try{
			List list = countInfoServiceImpl.queryOrderDetailedList(orderDetailedListVO);
			CsvExportUtil.doCsvExport(response, list);
		}catch(Exception e){
			log.error("queryOrderDetailedList error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
		log.info("In queryOrderDetailedListCsv end!");	
		return ;
	}
	/**
	 * 
	 * @Title: queryCountInfo
	 * @Description: 运营信息统计 
	 * @param @param request
	 * @param @param response
	 * @param @param countInfoDTO
	 * @param @return   
	 * @return ModelAndView   
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryAuthUserDetailedList.shtml")
	@ResponseBody
	public ResultMap queryAuthUserDetailedList(HttpServletRequest request,
			HttpServletResponse response,AuthUserDetailedListVO authUserDetailedListVO,Pager pager) {
		
		
		log.info("In queryOrderDetailedList begin!");
		
		try{
			
			authUserDetailedListVO.setBegin(pager.getStartIndex());
			authUserDetailedListVO.setPageSize(pager.getPageSize());
			
			
			int count = countInfoServiceImpl.queryAuthUserDetailedListCount(authUserDetailedListVO);
			
			pager.setTotalCount(count);
			
			List<AuthUserDetailedListVO> list;
			if(count>0){
				list = countInfoServiceImpl.queryAuthUserDetailedList(authUserDetailedListVO);
			}else{
				list = Collections.EMPTY_LIST;
			}
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			resultMap.setAttribute("list",list);
			resultMap.setAttribute("pager",pager);
		}catch(Exception e){
			log.error("queryOrderDetailedList error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
		log.info("In queryOrderDetailedList end!");	
		
		return resultMap;
	}
	/**
	 * 
	 * @Title: queryAuthUserDetailedListCsv
	 * @Description: 导出认证用户清单
	 * @param @param request
	 * @param @param response
	 * @param @param countInfoDTO
	 * @param @return   
	 * @return ModelAndView   
	 * @throws
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/queryAuthUserDetailedListCsv.shtml")
	public void queryAuthUserDetailedListCsv(HttpServletRequest request,
			HttpServletResponse response,AuthUserDetailedListVO authUserDetailedListVO) {
		
		
		log.info("In queryOrderDetailedList begin!");
		
		try{
			
			List list = countInfoServiceImpl.queryAuthUserDetailedList(authUserDetailedListVO);
			CsvExportUtil.doCsvExport(response, list);
		}catch(Exception e){
			log.error("queryOrderDetailedList error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
		log.info("In queryOrderDetailedList end!");	
		return ;
	}
	
	/**
	 * 
	 * @Title: queryAuthUserDetailedListCsv
	 * @Description: 销售清单
	 * @param @param request
	 * @param @param response
	 * @param @param countInfoDTO
	 * @param @return   
	 * @return ModelAndView   
	 * @throws
	 */
	@RequestMapping("/querySalesPerformance.shtml")
	@ResponseBody
	public ResultMap querySalesPerformance(HttpServletRequest request,
			HttpServletResponse response,SalesPerformanceVO salesPerformanceVO) {
		
		
		log.info("In querySalesPerformance begin!");
		ResultMap resultMap = new ResultMap();
		try{
			
			List<SalesPerformanceVO> list = countInfoServiceImpl.querySalesPerformance(salesPerformanceVO);
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			resultMap.setAttribute("list",list);
		}catch(Exception e){
			log.error("querySalesPerformance error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
		log.info("querySalesPerformance end!");	
		return resultMap;
	}
	
	
	/**
	 * 
	 * @Title: querySalesPerformanceCsv
	 * @Description: 导出销售清单
	 * @param @param request
	 * @param @param response
	 * @param @param salesPerformanceVO
	 * @param @return   
	 * @return ModelAndView   
	 * @throws
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/querySalesPerformanceCsv.shtml")
	public void querySalesPerformanceCsv(HttpServletRequest request,
			HttpServletResponse response,SalesPerformanceVO salesPerformanceVO) {
		
		
		log.info("In querySalesPerformanceCsv begin!");
		
		try{
			
			List list = countInfoServiceImpl.querySalesPerformance(salesPerformanceVO);
			CsvExportUtil.doCsvExport(response, list);
		}catch(Exception e){
			log.error("queryOrderDetailedList error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
		log.info("In querySalesPerformanceCsv end!");	
		return ;
	}
	
	//合并老系统统计代码
	/**
	 * 
	 * @Title: queryOperateStatistics
	 * @Description: 运营统计报表
	 * @param @param request
	 * @param @param response
	 * @param @param countInfoDTO
	 * @param @return   
	 * @return ModelAndView   
	 * @throws
	 */
	@RequestMapping("/queryOperateStatistics.shtml")
	@ResponseBody
	public ResultMap  queryOperateStatistics(HttpServletRequest request,
			HttpServletResponse response) {
		ResultMap  map =  new ResultMap();
		
		log.info("In queryOperateStatistics begin!");
		
		try{
			
			List<Map<String,Object>> list = countInfoServiceImpl.queryOperateStatistics();
			if(list!=null&&list.size()>1){
				//第一条同步
				Map<String, Object> first = list.get(0);
				//查询理财师总量和该用量
				FaUserDTO faUserDTO=new FaUserDTO();
				int registeredFinancialNumLJ = faUserServiceImpl.queryAllFaUserInfoCount(faUserDTO);
				first.put("registeredFinancialNumLJ", registeredFinancialNumLJ);
				faUserDTO.setuRole("Y");
				int authFinancialNumLJ = faUserServiceImpl.queryAllFaUserInfoCount(faUserDTO);
				first.put("authFinancialNumLJ", authFinancialNumLJ);
				Map<String, Object> second = list.get(1);
				BigDecimal oldRegisteredFinancial=(BigDecimal) second.get("registeredFinancialNumLJ");
				first.put("registeredFinancialNum", registeredFinancialNumLJ-oldRegisteredFinancial.intValue());
				BigDecimal oldAuthFinancialNumLJ=(BigDecimal) second.get("authFinancialNumLJ");
				first.put("authFinancialNum", authFinancialNumLJ-oldAuthFinancialNumLJ.intValue());
			}
			
			map.setAttribute("list", list);
			map.setStatus(STATUS.SUCCESS);
			map.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryOperateStatistics error !",e);
			map.setStatus(STATUS.FAILE);
			map.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
		log.info("In queryOperateStatistics end!");	
		return map;
	}
	/**
	 * 根据月份查询注册用户数
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@RequestMapping("/queryFaUserRegisterByMonthCount.shtml")
	@ResponseBody
	public ResultMap queryFaUserRegisterByMonthCount(String startDate, String endDate){
		log.info("In queryFaUserRegisterByMonthCount begin!");
		
		ResultMap map = new ResultMap();
		
		Map<String, Object> params = new HashMap<String, Object>();
		if(!StringUtils.isBlank(startDate)){
			params.put("startDate", startDate);
		}
		if(!StringUtils.isBlank(endDate)){
			params.put("endDate", endDate);
		}
		try {
			List<Map<String, Object>> list = countInfoServiceImpl.queryFaUserRegisterByMonthCount(params);
			
			map.setAttribute("list", list);
			map.setStatus(STATUS.SUCCESS);
			map.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("queryOperateStatistics error !",e);
			map.setStatus(STATUS.FAILE);
			map.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return map;
	}
	/**
	 * 根据月份查询注册用户数
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@RequestMapping("/queryFaUserRoleCount.shtml")
	@ResponseBody
	public ResultMap queryFaUserRoleCount(String startDate, String endDate){
		log.info("In queryFaUserRoleCount begin!");
		
		ResultMap map = new ResultMap();
		
		Map<String, Object> params = new HashMap<String, Object>();
		if(!StringUtils.isBlank(startDate)){
			params.put("startDate", startDate);
		}
		if(!StringUtils.isBlank(endDate)){
			params.put("endDate", endDate);
		}
		try {
			List<Map<String, Object>> list = countInfoServiceImpl.queryFaUserRoleCount(params);
			
			map.setAttribute("list", list);
			map.setStatus(STATUS.SUCCESS);
			map.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("queryFaUserRoleCount error !",e);
			map.setStatus(STATUS.FAILE);
			map.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return map;
	}
	/**
	 * 
	 * @Title: queryOrderCountByMonth
	 * @Description: 订单 -月销售统计
	 * @param @param request
	 * @param @param response
	 * @param @return   
	 * @return ModelAndView   
	 * @throws
	 */
	@RequestMapping("/queryOrderCountByMonth.shtml")
	@ResponseBody
	public ResultMap  queryOrderCountByMonth(HttpServletRequest request) {
		ResultMap  map =  new ResultMap();
		
		log.info("In queryOrderCountByMonth begin!");
		
		try{
			List<Map<String,Object>> list = countInfoServiceImpl.queryOrderCountByMonth();
			map.setAttribute("list", list);
			map.setStatus(STATUS.SUCCESS);
			map.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryOrderCountByMonth error !",e);
			map.setStatus(STATUS.FAILE);
			map.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
		log.info("In queryOrderCountByMonth end!");	
		return map;
	}
	/**
	 * 
	 * @Title: queryOrderUserPer
	 * @Description: 订单用户占认证比例
	 * @param @param request
	 * @param @param response
	 * @param @return   
	 * @return ModelAndView   
	 * @throws
	 */
	@RequestMapping("/queryOrderUserPer.shtml")
	@ResponseBody
	public ResultMap  queryOrderUserPer(HttpServletRequest request) {
		ResultMap  map =  new ResultMap();
		
		log.info("In queryOrderUserPer begin!");
		
		try{
			Map<String,Object> dto = countInfoServiceImpl.queryOrderUserPer();
			Object allUserCount=dto.get("allUserCount");
			Object noHasOrderUserCount=dto.get("noHasOrderUserCount");
			if(allUserCount!=null&&noHasOrderUserCount!=null){
				double userCount=Double.parseDouble(allUserCount+"");
				double orderUserCount=Double.parseDouble(noHasOrderUserCount+"");
				if(orderUserCount==0){
					dto.put("orderUserAuthPer", "1");
				}else{
					String format = df.format(userCount/(userCount-orderUserCount));
					dto.put("orderUserAuthPer", format);
				}
			}
			
			map.setAttribute("dto", dto);
			map.setStatus(STATUS.SUCCESS);
			map.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryOrderUserPer error !",e);
			map.setStatus(STATUS.FAILE);
			map.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
		log.info("In queryOrderUserPer end!");	
		return map;
	}
	/**
	 * 订单-认证理财师role占比
	 * @param
	 * @return
	 * @throws
	 */
	@RequestMapping("/queryOrderFaUserRoleProportion.shtml")
	@ResponseBody
	public ResultMap queryOrderFaUserRoleProportion(){
		log.info("In queryOrderFaUserRoleProportion begin!");
		ResultMap map = new ResultMap();
		try {
			List<Map<String, Object>> list = countInfoServiceImpl.queryOrderFaUserRoleProportion( new HashMap<String, Object>());
			map.setAttribute("list", list);
			map.setStatus(STATUS.SUCCESS);
			map.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("queryOrderFaUserRoleProportion error !",e);
			map.setStatus(STATUS.FAILE);
			map.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return map;
	}
	/**
	 * 认证-理财师role占比
	 * @param
	 * @return
	 * @throws
	 */
	@RequestMapping("/queryFaUserRoleProportion.shtml")
	@ResponseBody
	public ResultMap queryFaUserRoleProportion(){
		log.info("In queryFaUserRoleProportion begin!");
		ResultMap map = new ResultMap();
		try {
			List<Map<String, Object>> list = countInfoServiceImpl.queryFaUserRoleProportion( new HashMap<String, Object>());
			map.setAttribute("list", list);
			map.setStatus(STATUS.SUCCESS);
			map.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("queryFaUserRoleProportion error !",e);
			map.setStatus(STATUS.FAILE);
			map.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return map;
	}
	/***
	 * 
	
	* @Title: queryUserTotalSales
	
	* @Description:理财师统计top
	
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/queryUserTotalSales.shtml")
	@ResponseBody
	public ResultMap queryUserTotalSales(HttpServletRequest request,CountInfoDTO countInfo){
		log.info("In queryUserTotalSales begin!");
		ResultMap map = new ResultMap();
		try {
			List<Map<String, Object>> list = countInfoServiceImpl.queryUserTotalSales(countInfo);
//			for (Map<String, Object> map2 : list) {
//				String faId=String.valueOf(map2.get("faId"));
//				map2.put("faId",SecureUtil.encodeBase64(faId));
//			}
			map.setAttribute("list", list);
			map.setStatus(STATUS.SUCCESS);
			map.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("queryUserTotalSales error !",e);
			map.setStatus(STATUS.FAILE);
			map.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return map;
	}
}
